<script setup lang="ts">
import { ref, onUnmounted } from 'vue';
import { loginByPassword, getSMSCode, loginByCode } from '@/services/user';
import { Toast, type FormInstance } from 'vant';
// 导入保存信息的store
import { useUserStore } from '@/stores/user';
// 导入路由跳转的route以及router
import { useRoute, useRouter } from 'vue-router';

import CpNavBar from '@/components/CpNavBar.vue';

//
const router = useRouter();
const route = useRoute();
// 创建保存用户信息的store方法
const users = useUserStore();
// 定义页面数据
const mobile = ref('');
const password = ref('');
const smsCode = ref('');
const form = ref<FormInstance>();
let timerId: number; // 不需要响应所以没有ref
// 页面状态数据
const isAgree = ref(false);
const isShowPwd = ref(false);
const isPwdLogin = ref(true);
const counter = ref(0);
// 表单校验规则
const mobileRules = [
  { required: true, message: '请输入手机号' },
  { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' },
];
const passwordRules = [
  { required: true, message: '请输入密码' },
  { pattern: /^\w{8,24}$/, message: '密码需8-24个字符' },
];
const codeRules = [
  { required: true, message: '请输入验证码' },
  { pattern: /^\d{6}$/, message: '验证码6个数字' },
];
// 生命周期函数
onUnmounted(() => {
  // 组件卸载时清理定时器
  window.clearInterval(timerId);
});
// 发送验证码事件处理函数
const sendSms = async () => {
  // 如果计时中，返回不响应
  if (counter.value > 0) return;
  console.log('发送验证码事件处理函数开始');
  // 验证手机号字段
  await form.value?.validate('mobile');
  console.log('手机号验证成功');
  // 开启倒计时
  counter.value = 10;
  window.clearInterval(timerId);
  timerId = window.setInterval(() => {
    counter.value -= 1;
    if (counter.value <= 0) {
      window.clearInterval(timerId);
      console.log('清空了定时器', timerId);
    }
  }, 1000);
  // 通知服务器发送验证码
  const res = await getSMSCode(mobile.value, 'login');
  console.log(res);
};
// 表单数据验证成功后，执行这个回调函数
const login = async (values: { mobile: string; password: string }) => {
  // 验证用户是否勾选登录协议
  if (!isAgree.value) return Toast('请勾选我已同意');
  console.log('可以登录了', values);
  // 密码登录
  if (isPwdLogin.value) {
    const user = await loginByPassword(values.mobile, values.password);
    console.log(user);
    // 保存用户信息到 userStore
    users.setUser(user);
    // 如果有回跳地址就进行回跳，没有跳转到个人中心
    // router.push((route.query.returnURL as string) || '/user');
    // 上面的代码等价于下面
    if (route.query.returnURL) {
      router.push(route.query.returnURL as string);
    } else {
      router.push('/user');
    }
    Toast.success('登录成功');
  } else {
    // 验证码登录
    const user = await loginByCode(values.mobile, smsCode.value);
    console.log(user);
    // 保存用户信息到 userStore
    users.setUser(user);
    router.push((route.query.returnURL as string) || '/user');
    Toast.success('登录成功');
  }
};
const clickRight = () => {
  console.log('父组件调用者执行');
};
</script>

<template>
  <div class="login">
    <!-- 自定义导航栏 -->
    <CpNavBar title="登录" rightText="注册" @click-right="clickRight" />

    <!-- 登录方式 -->
    <div class="login-head">
      <span class="title">{{ isPwdLogin ? '密码登录' : '短信登录' }}</span>
      <a class="sms" href="javascript:;" @click="isPwdLogin = !isPwdLogin">
        <span>{{ isPwdLogin ? '短信验证码登录' : '密码登录' }}</span>
        <van-icon name="arrow"></van-icon>
      </a>
    </div>

    <!-- 登录表单 -->
    <div class="login-form">
      <van-form autocomplete="off" @submit="login" ref="form">
        <van-field
          name="mobile"
          :rules="mobileRules"
          v-model="mobile"
          placeholder="请输入手机号"
          type="tel"
        ></van-field>
        <van-field
          v-if="isPwdLogin"
          name="password"
          :rules="passwordRules"
          v-model="password"
          placeholder="请输入密码"
          :type="isShowPwd ? 'text' : 'password'"
        >
          <template #button>
            <cp-icon
              @click="isShowPwd = !isShowPwd"
              :name="isShowPwd ? 'login-eye-on' : 'login-eye-off'"
            ></cp-icon>
          </template>
        </van-field>
        <!-- 验证码输入框 -->
        <van-field
          v-else
          placeholder="请输入验证码"
          :rules="codeRules"
          v-model="smsCode"
          name="smsCode"
        >
          <template #button>
            <span :class="['btn-send', counter > 0 ? 'disabled' : '']" @click="sendSms">{{
              counter > 0 ? counter + 's后再次发送' : '发送验证码'
            }}</span>
          </template>
        </van-field>
        <div class="cp-cell">
          <van-checkbox v-model="isAgree">
            <span>我已同意</span>
            <a href="javascript:;">用户协议</a>
            <span>及</span>
            <a href="javascript:;">隐私条款</a>
          </van-checkbox>
        </div>
        <div class="cp-cell">
          <van-button block round type="primary" native-type="submit">登 录</van-button>
        </div>
        <div class="cp-cell">
          <a href="javascript:;">忘记密码？</a>
        </div>
      </van-form>
    </div>

    <!-- 第三方登录 -->
    <div class="login-other">
      <van-divider>第三方登录</van-divider>
      <a
        class="icon"
        href="https://graph.qq.com/oauth2.0/authorize?client_id=102015968&response_type=token&scope=all&redirect_uri=http%3A%2F%2Fconsult-patients.itheima.net%2Flogin%2Fcallback"
      >
        <img src="@/assets/qq.svg" alt="qq-icon" />
      </a>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login {
  .login-head {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30px;

    .title {
      font-weight: bold;
      font-size: 24px;
    }
    .sms {
      span {
        font-size: 16px;
      }
    }
  }
  // 登录表单
  .login-form {
    padding: 0 14px;
    .cp-cell {
      display: flex;
      height: 52px;
      padding: 14px 16px;
      box-sizing: border-box;
      align-items: center;
      .van-checkbox {
        a {
          color: var(--cp-primary);
          margin: 0 6px;
        }
      }
      .btn-send {
        color: var(--cp-primary);
        &.disabled {
          color: rgba(22, 194, 163, 0.5);
        }
      }
    }
  }
  // 第三方登录
  .login-other {
    margin-top: 60px;
    padding: 0 30px;
    .icon {
      display: flex;
      justify-content: center;
      img {
        width: 36px;
        height: 36px;
        padding: 4px;
      }
    }
  } // 第三方登录
  .login-other {
    margin-top: 60px;
    padding: 0 30px;
    .icon {
      display: flex;
      justify-content: center;
      img {
        width: 36px;
        height: 36px;
        padding: 4px;
      }
    }
  }
}
</style>
